package com.penjin.android.activity.gongzuo;

import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.XAxisValueFormatter;
import com.github.mikephil.charting.formatter.YAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.penjin.android.R;
import com.penjin.android.activity.PenjinBaseActivity;
import com.penjin.android.activity.kaoqin.DepartmentLateBean;
import com.penjin.android.constants.HttpConstants;
import com.penjin.android.domain.MyYAxisValueFormatter;
import com.penjin.android.domain.PenjinCompany;
import com.penjin.android.domain.PenjinDate;
import com.penjin.android.domain.PenjinStaff;
import com.penjin.android.domain.PenjinUser;
import com.penjin.android.http.HttpService;
import com.penjin.android.service.UserService;
import com.penjin.android.utils.HttpUtil;
import com.penjin.android.utils.ToastHelper;
import com.penjin.android.view.CustomProgressDialog;
import com.penjin.android.view.TitleBarView;
import com.penjin.android.widget.PenjinCircleNumber;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;

/**
 * Created by maotiancai on 2016/1/7.
 */
public class PenjinBaobiaoActivity extends PenjinBaseActivity implements OnChartValueSelectedListener, View.OnClickListener {

    PenjinUser penjinUser;
    PenjinCompany penjinCompany;
    PenjinStaff penjinStaff;
    PenjinDate nowDate;
    PenjinDate pickDate;

    private TitleBarView titleBarView;

    HttpService httpService;
    TextHttpResponseHandler handler;

    boolean isLoading = true;
    boolean isFirstLoading = false;
    CustomProgressDialog progressDialog;

    BarChart barChart;
    int chartType = 0;
    PenjinCircleNumber chidao;
    PenjinCircleNumber qianka;
    PenjinCircleNumber weiqian;
    PenjinCircleNumber qingjia;
    PenjinCircleNumber chuchai;
    PenjinCircleNumber waiqin;
    PenjinCircleNumber jiaban;
    PenjinCircleNumber tiaoxiu;

    PenjinBaobiaoBean dataBean;
    ArrayList<PenjinDepartmentChartBean> dataList = new ArrayList<PenjinDepartmentChartBean>();
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                showChart(chartType);
                setData(dataBean);
            } else if (msg.what == 2) {
                isLoading = false;
            }
        }
    };

    View preview;
    View next;
    TextView currentDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_activity_penjin_baobiao);
        initData();
        initHttp();
        initView();
    }

    private void initData() {
        UserService userService = UserService.getInstance(getApplicationContext());
        penjinUser = userService.getCurrentUser();
        if (penjinUser == null) {
            finish();
            ToastHelper.showNotLogin(getApplicationContext());
        } else {
            if (penjinUser.isInCompany()) {
                penjinCompany = userService.getCurrentCompany();
                penjinStaff = userService.getCurrentStaff();
            } else {
                ToastHelper.showNotBindCompany(getApplicationContext());
            }
        }
        nowDate = new PenjinDate(new Date());
        pickDate = new PenjinDate(new Date());
    }

    private void initHttp() {
        httpService = HttpService.getInstance(getApplicationContext());
        handler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                isLoading = false;
                progressDialog.dismiss();
                if (s != null) {
                    System.out.println(s);
                }
                ToastHelper.showServerError(getApplicationContext());
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                progressDialog.dismiss();
                try {
                    dataBean = new PenjinBaobiaoBean();
                    JSONObject jsonObject = new JSONObject(s);
                    boolean result = jsonObject.getBoolean("result");
                    if (result) {
                        dataBean.miss = jsonObject.getInt("miss");
                        dataBean.late = jsonObject.getInt("late");
                        dataBean.early = jsonObject.getInt("early");
                        dataBean.nodaka = jsonObject.getInt("nodaka");
                        dataBean.chuchai = jsonObject.getInt("chuchai");
                        dataBean.qingjia = jsonObject.getInt("qingjia");
                        dataBean.jiaban = jsonObject.getInt("jiaban");
                        dataBean.qianka = jsonObject.getInt("qianka");
                        dataBean.tiaoxiu = jsonObject.getInt("tiaoxiu");
                        dataBean.yidi = jsonObject.getInt("yidi");
                        dataList.clear();
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (int j = 0; j < jsonArray.length(); j++) {
                            JSONObject object = jsonArray.getJSONObject(j);
                            PenjinDepartmentChartBean bean = new PenjinDepartmentChartBean();
                            bean.departname = object.getString("department");
                            bean.late = object.getInt("late");
                            bean.early = object.getInt("early");
                            bean.miss = object.getInt("miss");
                            dataList.add(bean);
                        }
                        mHandler.sendEmptyMessage(1);
                    } else {
                        mHandler.sendEmptyMessage(2);
                    }

                } catch (Exception e) {
                    isLoading = false;
                    mHandler.sendEmptyMessage(2);
                }
                System.out.println(s);
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        // penjinCircleNumber.start();
        if (!isFirstLoading) {
            isLoading = true;
            lauchRequest();
        }

    }

    private void initView() {
        barChart = (BarChart) findViewById(R.id.barChart);
        titleBarView = (TitleBarView) findViewById(R.id.titleBarView);
        titleBarView.setTitleBarListener(new TitleBarView.TitleBarListener() {
            @Override
            public void left(View view) {
                finish();
            }

            @Override
            public void center(View view) {

            }

            @Override
            public void right(View view) {
                chartType = (chartType + 1) % 3;
                showChart(chartType);
            }
        });
        progressDialog = CustomProgressDialog.createDialog(this);
        progressDialog.setMessage("请稍后...");
        chidao = (PenjinCircleNumber) findViewById(R.id.chidaoCircle);
        qianka = (PenjinCircleNumber) findViewById(R.id.qiankaCircle);
        weiqian = (PenjinCircleNumber) findViewById(R.id.weiqianCircle);
        qingjia = (PenjinCircleNumber) findViewById(R.id.qingjiaCircle);
        chuchai = (PenjinCircleNumber) findViewById(R.id.chuchaiCircle);
        waiqin = (PenjinCircleNumber) findViewById(R.id.waiqinCircle);
        jiaban = (PenjinCircleNumber) findViewById(R.id.jiabanCircle);
        tiaoxiu = (PenjinCircleNumber) findViewById(R.id.tiaoxiuCircle);
        preview = findViewById(R.id.leftDayBtn);
        next = findViewById(R.id.rightDayBtn);
        currentDate = (TextView) findViewById(R.id.currentDate);
        preview.setOnClickListener(this);
        next.setOnClickListener(this);
        initBarChart();
    }

    private void initBarChart() {
        barChart.setOnChartValueSelectedListener(this);

        barChart.setDrawBarShadow(false);
        barChart.setDrawValueAboveBar(true);
        barChart.setDescription("");

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        barChart.setMaxVisibleValueCount(60);

        // scaling can now only be done on x- and y-axis separately
        barChart.setPinchZoom(false);

        barChart.setDrawGridBackground(false);
        // barChart.setDrawYLabels(false);

        // mTf = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");

        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //xAxis.setTypeface(mTf);
        xAxis.setDrawGridLines(false);
        xAxis.setSpaceBetweenLabels(2);


        YAxis leftAxis = barChart.getAxisLeft();
        // leftAxis.setTypeface(mTf);
        leftAxis.setLabelCount(8, true);
        leftAxis.setValueFormatter(null);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setDrawGridLines(true);

        YAxis rightAxis = barChart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        //rightAxis.setTypeface(mTf);
        rightAxis.setLabelCount(8, true);
        rightAxis.setValueFormatter(null);
        rightAxis.setSpaceTop(15f);

        Legend l = barChart.getLegend();
        l.setPosition(Legend.LegendPosition.BELOW_CHART_LEFT);
        l.setForm(Legend.LegendForm.SQUARE);
        l.setFormSize(9f);
        l.setTextSize(11f);
        l.setXEntrySpace(4f);
    }

    private void lauchRequest() {
        progressDialog.show();
        try {
            RequestParams requestParams = new RequestParams();
            requestParams.put("companyId", penjinCompany.getCompanyId());
            requestParams.put("userName", penjinUser.getPhone());
            String date = pickDate.year + "/" + pickDate.month + "/" + pickDate.date;
            requestParams.put("date", date);
            httpService.postRequest(this, HttpConstants.HOST + HttpConstants.KaoqinManageReport, requestParams, handler);
        } catch (Exception e) {
            progressDialog.dismiss();
            ToastHelper.showDNSError(getApplicationContext());
            isLoading = false;
        }
    }

    private void setData(PenjinBaobiaoBean bean) {
        String txt = pickDate.year + "年" + pickDate.month + "月" + pickDate.date + "日";
        currentDate.setText(txt);
        if (!isFirstLoading) {
            chidao.initData(bean.late);
            qianka.initData(bean.qianka);
            weiqian.initData(bean.nodaka);
            qingjia.initData(bean.qingjia);
            chuchai.initData(bean.chuchai);
            waiqin.initData(bean.yidi);
            jiaban.initData(bean.jiaban);
            tiaoxiu.initData(bean.tiaoxiu);

            chidao.start();
            qianka.start();
            weiqian.start();
            qingjia.start();
            chuchai.start();
            waiqin.start();
            jiaban.start();
            tiaoxiu.start();
            isFirstLoading = true;
        } else {
            chidao.setTextNumber(bean.late);
            qianka.setTextNumber(bean.qianka);
            weiqian.setTextNumber(bean.nodaka);
            qingjia.setTextNumber(bean.qingjia);
            chuchai.setTextNumber(bean.chuchai);
            waiqin.setTextNumber(bean.yidi);
            jiaban.setTextNumber(bean.jiaban);
            tiaoxiu.setTextNumber(bean.tiaoxiu);
        }


        isLoading = false;
    }

    private void showChart(int type) {
        if (dataList == null || dataList.isEmpty()) {
            return;
        } else {
            setChart(dataList, type);
        }
    }

    private void setChart(ArrayList<PenjinDepartmentChartBean> list, int type) {
        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.VORDIPLOM_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);
        colors.add(ColorTemplate.getHoloBlue());


        int count = list.size();
        ArrayList<String> xVals = new ArrayList<String>();
        for (int i = 0; i < count; i++) {
            xVals.add(list.get(i).departname);
        }

        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

        for (int i = 0; i < count; i++) {
            float val = 0;
            switch (type) {
                case 0://late
                    val = list.get(i).late;
                    yVals1.add(new BarEntry(val, i));
                    break;
                case 1://early
                    val = list.get(i).early;
                    yVals1.add(new BarEntry(val, i));
                    break;
                case 2://miss
                    val = list.get(i).miss;
                    yVals1.add(new BarEntry(val, i));
                    break;
            }
        }
        BarDataSet set1 = null;
        switch (type) {
            case 0:
                set1 = new BarDataSet(yVals1, "迟到统计");
                break;
            case 1:
                set1 = new BarDataSet(yVals1, "早退统计");
                break;
            case 2:
                set1 = new BarDataSet(yVals1, "缺勤统计");
                break;
        }

        set1.setBarSpacePercent(35f);
        set1.setColors(colors);


        ArrayList<BarDataSet> dataSets = new ArrayList<BarDataSet>();
        dataSets.add(set1);

        BarData data = new BarData(xVals, dataSets);
        data.setDrawValues(false);
        barChart.setData(data);
        barChart.invalidate();
    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
        if (e == null) {
            return;
        }
        PenjinDepartmentChartBean bean = dataList.get(e.getXIndex());
        String msg = "";
        boolean isEmptyValue = false;
        switch (chartType) {
            case 0:
                msg += bean.departname + "迟到" + bean.late + "人";
                isEmptyValue = bean.late == 0 ? true : false;
                break;
            case 1:
                msg += bean.departname + "早退" + bean.early + "人";
                isEmptyValue = bean.early == 0 ? true : false;
                break;
            case 2:
                msg += bean.departname + "缺勤" + bean.miss + "人";
                isEmptyValue = bean.miss == 0 ? true : false;
                break;
        }
        if (!isEmptyValue)
            ToastHelper.showMessage(msg, getApplicationContext());

    }

    @Override
    public void onNothingSelected() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.leftDayBtn:
                if (!isLoading) {
                    if (HttpUtil.isNetworkAvailable(this)) {
                        pickDate = PenjinDate.getPreDay(pickDate);
                        isLoading = true;
                        lauchRequest();
                    } else {
                        ToastHelper.showNoNetwork(this);
                    }
                }
                break;
            case R.id.rightDayBtn:
                if (!isLoading) {
                    if (HttpUtil.isNetworkAvailable(this)) {
                        if (!pickDate.isSameDay(nowDate)) {
                            pickDate = PenjinDate.getNextDay(pickDate);
                            isLoading = true;
                            lauchRequest();
                        }
                    } else {
                        ToastHelper.showNoNetwork(this);
                    }
                }
                break;
        }
    }
}